from django_redis import get_redis_connection
from rest_framework import serializers

from users.models import *
import django.contrib.auth.password_validation as validators

# 注册
class ZhuceSerializer(serializers.ModelSerializer):
    token = serializers.CharField(read_only=True)
    password = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(required=True, write_only=True)
    avatar = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'mobile',
            'sms_code',
            'avatar',
            'password',
            'token',
        ]

    def validate(self, attrs):
        """校验验证码"""
        sms_code = attrs['sms_code']
        mobile = attrs['mobile']
        # 根据手机号取出验证码
        redis_conn = get_redis_connection('verify_code')
        sms = redis_conn.get('sms_%s' % mobile)
        if not sms:
            raise serializers.ValidationError('验证码过期')
        if sms_code != sms.decode():
            raise serializers.ValidationError('验证码错误')
        return attrs

    def create(self, validated_data):
        del validated_data['sms_code']
        user = User.objects.create_user(**validated_data)
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user

# 标签序列化器
class LabelsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'

# 提的问题
class QuestionsSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(read_only=True)
    labels = LabelsSerializer(read_only=True, many=True)
    class Meta:
        model = Question
        fields = '__all__'

# 回答的问题序列化器
class ReplySerialzier(serializers.ModelSerializer):
    class Meta:
        model = Reply
        fields = '__all__'

# 收集的文章
class ArticlesSerialzier(serializers.ModelSerializer):
    user = ZhuceSerializer(read_only=True)
    collected_users = serializers.PrimaryKeyRelatedField(
        label='谁收藏了该文章',
        read_only=True,
        many=True
    )
    class Meta:
        model = Article
        fields = '__all__'

# 收藏的企业
class EnterpisesSerialzier(serializers.ModelSerializer):
    recruits = serializers.PrimaryKeyRelatedField(read_only=True,many=True)
    class Meta:
        model = Enterprise
        fields = ['id','name','labels','logo','summary','recruits']


# 用户中心详情
class UserViewSerializer(serializers.ModelSerializer):
    password = serializers.CharField(style={'input_type': 'password'}, write_only=True, allow_null=True)
    labels = LabelsSerializer(read_only=True,many=True) # 标签
    questions = QuestionsSerializer(read_only=True,many=True) # 提的问题
    answer_question = ReplySerialzier(read_only=True,many=True)# 回答的问题
    collected_articles = ArticlesSerialzier(read_only=True,many=True) # 收集的文章
    enterpises = EnterpisesSerialzier(read_only=True,many=True) # 收藏的企业
    class Meta:
        model = User
        fields = '__all__'

    def validate_password(self, data):
        validators.validate_password(password=data, user=User)
        return data